import fs from "fs";
import db from "src/db/project";
import field from "src/config/field";
import res from "src/utils/response";
import { getInstallPath, getDeployFolderName } from "src/utils";

export async function add(ctx: Context, params: any) {
  const row: any = await db.queryOne(params, "repository_address");
  if (row) {
    if (row.del_flag === 0) {
      await db.modify({
        ...params,
        id: row.id,
        del_flag: 1,
        install_status: 0,
        git_clone_status: 0,
        install_path: getInstallPath(params),
        deploy_folder_name: getDeployFolderName(params),
      });
      ctx.body = res.ok();
    } else {
      ctx.body = res.fail("该项目已存在");
    }
  } else {
    await db.add({
      ...params,
      install_path: getInstallPath(params),
      deploy_folder_name: getDeployFolderName(params),
    });
    ctx.body = res.ok();
  }
}

export async function remove(ctx: Context, params: any) {
  const row: any = await db.queryOne(params, "id");
  if (row && row.del_flag === 1) {
    fs.rmSync(row.install_path, { recursive: true, force: true });
    await db.remove(params.id);
    ctx.body = res.ok();
  } else {
    ctx.body = res.fail("该项目不存在");
  }
}

export async function modify(ctx: Context, params: any) {
  const row: any = await db.queryOne(params, "id");
  if (row && row.del_flag === 1) {
    await db.modify({ ...params, id: row.id });
    ctx.body = res.ok();
  } else {
    ctx.body = res.fail("该项目不存在");
  }
}

export async function query(ctx: Context, params: any) {
  const rows = await db.query(field.project);
  ctx.body = res.ok(rows);
}
